package com.android.bookgarden;

import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.HomeAdvBean;
import com.android.bookgarden.bean.HomeDataBean;
import com.android.bookgarden.bean.SmsMode;
import com.android.bookgarden.bean.VersionBean;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.db.XutilsDataDao;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.tabfragment.Tab1Fragment;
import com.android.bookgarden.tabfragment.Tab4Fragment;
import com.android.bookgarden.tabfragment.TestIndexFragment;
import com.android.bookgarden.utli.DownLoadApp;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.SpUtils;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.BaseDialog;
import com.android.bookgarden.views.LoadingDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements RealtConstract.View {


    @BindView(R.id.fragment)
    FrameLayout fragment;
    @BindView(R.id.tab1)
    RadioButton tab1;

    @BindView(R.id.tab4)
    RadioButton tab4;
    @BindView(R.id.mHomeRadioGroup)
    RadioGroup mHomeRadioGroup;

//    private Tab1Fragment tab1Fragment;
    //以前的fragment不用，用现在下面这个新的
    private TestIndexFragment tab1Fragment;
    private Tab4Fragment tab4Fragment;
    private Fragment currentFragment;
    private FragmentManager fm;
    public String token ;
    public static MainActivity mainActivity;

    private ArrayList<HomeAdvBean> advList;
    private List<SmsMode> modeList;
    private RealtConstract.Presenter presenter;
    private XutilsDataDao dataDao;
    private VersionBean versionBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(){
        dataDao = XutilsDataDao.getInstance(this);
        presenter = new BasePersenter(this,this);
        Map map =null;
        presenter.loadData(map,"", Apis.DESCSMS_KEY,1001);
        presenter.loadDataHeader(null, "", Apis.APP_VERSION  , 1002, Utlis.getHeadler(this), HttpType.GET);

        init();
    }

    public void init(){
        advList = (ArrayList<HomeAdvBean>) getIntent().getSerializableExtra("adv");
        mainActivity = this;
        token = SpUtils.getInstance().getString(this,"token","");
        this.setStates("#ffffff");
        fm = getSupportFragmentManager();
        tab1Fragment = new TestIndexFragment();
        tab4Fragment = new Tab4Fragment();
        setSelected(0);

        mHomeRadioGroup.check(R.id.tab1);
        mHomeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.tab1:
                        setSelected(0);
                        break;

                    case R.id.tab4:
                        setSelected(1);
                        break;
                }
            }
        });
    }

    private void setSelected(int i) {

        switch (i) {
            case 0:
                showFragment(tab1Fragment);
                break;


            case 1:
                showFragment(tab4Fragment);
                break;

            default:

                break;

        }

    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment(Fragment fg) {

        FragmentTransaction transaction = fm.beginTransaction();

        //如果之前没有添加过
        if (!fg.isAdded()) {
            if (null != currentFragment) {
                transaction
                        .hide(currentFragment)
                        .add(R.id.fragment, fg);
            } else {
                transaction
                        .add(R.id.fragment, fg);
            }

        } else {
            transaction
                    .hide(currentFragment)
                    .show(fg);
        }

        //全局变量，记录当前显示的fragment
        currentFragment = fg;

        transaction.commit();

    }

    //
    @Override
    public void onRequestPermissions(String str, boolean z) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public List<HomeAdvBean> getAdvData(){
        return advList;
    }


    //声明一个long类型变量：用于存放上一点击“返回键”的时刻
    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void returnData(String data, int urlCode) {
        LogUtil.e("返回数据", data + "");
        if (TextUtils.isEmpty(data)) {
            return;
        }
        LoadingDialog.hideProgress();
        handler.obtainMessage(urlCode, data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        showToast("请求失败");
        LoadingDialog.hideProgress();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            switch (msg.what) {


                case 1001:
//                    refreshLayout.setRefreshing(false);
                    DataBean bean = Utlis.getDataBean(data);
                    if (null == bean) {
                        showToast("获取列表失败");
                        return;
                    }
                    if (bean.getCode() == 200) {
                        modeList = JsonUitl.stringToList(bean.getData(), SmsMode.class);
                        if (null == modeList || modeList.size() <= 0) {
                            return;
                        }
                        dataDao.deleteTable(SmsMode.class);
                        dataDao.insert(modeList);

                    } else {
                        showToast(bean.getMessage() + "");
                    }


                    break;

                case 1002:
                    bean = Utlis.getDataBean(data);
                    if (null == bean) {

                        return;
                    }
                    if (bean.getCode() == 200) {
                        versionBean = (VersionBean) JsonUitl.stringToObject(bean.getData(), VersionBean.class);

                        if (null!=versionBean){
                            if (versionBean.getVersioncode()>Utlis.getVersionCode(MainActivity.this)){

                            }
                            versionDialog();
                        }
                    }

                    break;



            }
        }
    };

    BaseDialog baseDialog;

    private void versionDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.update_app_view, null);
        TextView content = (TextView) view.findViewById(R.id.content);
        TextView sure = (TextView) view.findViewById(R.id.sure);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        if (null != versionBean) {
            content.setText(Html.fromHtml(versionBean.getContent()) );

        }

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                baseDialog.dismiss();
                DownLoadApp loadApp = new DownLoadApp(versionBean.getPath(), null, MainActivity.this);
                loadApp.showDownLoadProgress();
                loadApp.start();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseDialog.dismiss();


//                System.exit(0);
            }
        });
        baseDialog = new BaseDialog(this, view);
        baseDialog.showDialog();
    }
}

